package com.zhufei.servlet;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.zhufei.dao.Bbscs_UserdetailDAO;
import com.zhufei.dao.Bbscs_UserinfoDAO;
import com.zhufei.dao.NewsDao;
import com.zhufei.dao.Paging;
import com.zhufei.dao.UserDao;
import com.zhufei.dao.ZhuFeiUserInfoDao;
import com.zhufei.entity.User;
import com.zhufei.entity.UserInfo;

public class userServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public userServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	String action = request.getParameter("action");
	if(action == null){
		
	}
	
	if(action.equals("add")){
		this.add(request,response);
	}
	if(action.equals("manage")){
		this.manage(request,response);
	}
	if(action.equals("delete")){
		this.delete(request,response);
	}
	if(action.equals("edit")){
		this.edit(request,response);
	}
	if(action.equals("edited")){
		this.edited(request,response);
	}
	if(action.equals("signIn")){
		this.signIn(request,response);
	}
	if(action.equals("login")){
		this.login(request,response);
	}
	if(action.equals("findQuestion")){
		this.findQuestion(request,response);
	}
	if(action.equals("checkAnswer")){
		this.checkAnswer(request,response);
	}

	}

	private void checkAnswer(HttpServletRequest request,HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf8");
		HttpSession session = request.getSession();
		UserInfo userInfo = (UserInfo)session.getAttribute("userInfo");
		String answer = request.getParameter("answer");
		if(answer.equals(userInfo.getAnswer())){
			session.setAttribute("correct", "correct");
			response.sendRedirect("showPsw.jsp");
		}else{
			PrintWriter   out   =   response.getWriter(); 
			out.write( " <script   language=javascript> alert( '答案不匹配！ ');window.location.href= 'inputAnswer.jsp'; </script> "); 
			out.flush(); 
			out.close(); 			
		}
	}

	private void findQuestion(HttpServletRequest request,HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf8");
		String username = request.getParameter("username");
		ZhuFeiUserInfoDao userDao = new ZhuFeiUserInfoDao();
		UserInfo userInfo = userDao.getZhuFeiUserInfo(username);
		if(userInfo == null){
			PrintWriter   out   =   response.getWriter(); 
			out.write( " <script   language=javascript> alert( '不存在此用户，请重新输入！ ');window.location.href= 'findPsw.jsp'; </script> "); 
			out.flush(); 
			out.close(); 
		}else{
			HttpSession session = request.getSession();
			session.setAttribute("userInfo", userInfo);
			response.sendRedirect("inputAnswer.jsp");
		}
	}

	private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		ZhuFeiUserInfoDao userDao  = new ZhuFeiUserInfoDao();
		boolean isSucc = userDao.login(username, password);
		if(isSucc){
			HttpSession session = request.getSession();
			session.setAttribute("username", username);
			response.sendRedirect("index.jsp");	
		}else{
			PrintWriter   out   =   response.getWriter(); 
			out.write( " <script   language=javascript> alert( '用户名或密码输入错误，请重新输入！ ');window.location.href= 'index.jsp'; </script> "); 
			out.flush(); 
			out.close(); 	
		}
	}

	private void signIn(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf8");
		String username = request.getParameter("username");
		String password = request.getParameter("form_password1");
		String sex = request.getParameter("sex");
		String question = request.getParameter("question");
		String answer = request.getParameter("answer");
		String email = request.getParameter("email");
		ZhuFeiUserInfoDao userDao = new ZhuFeiUserInfoDao();
		boolean isSucc = userDao.insertZhuFeiUserInfo(username, password, email, sex, question, answer);
		if(isSucc){
			PrintWriter   out   =   response.getWriter(); 
			out.write( " <script   language=javascript> alert( '注册成功！ ');window.close(); </script> "); 
			out.flush(); 
			out.close(); 			
		}else{
			PrintWriter   out   =   response.getWriter(); 
			out.write( " <script   language=javascript> alert( '用户名重复，请用其他用户名！ ');window.location.href= 'signIn.jsp'; </script> "); 
			out.flush(); 
			out.close();			
		}
		
	}

	private void edited(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf8");
		

		
    	
		String real_name = null;
		String identification = null;
		String email = null;
		String qq = null;
		String tel = null;
		String changePic = null;
		String question = null;
		String answer = null;
		String motto = null;
		String profile = null;
	   final long MAX_SIZE = 3 * 1024 * 1024;// 设置上传文件最大为 3M
	   // 允许上传的文件格式的列表
	   final String[] allowedExt = new String[] { "jpg", "jpeg", "gif", "png"};
	   // 设置字符编码为UTF-8, 这样支持汉字显示
	   response.setCharacterEncoding("UTF-8");

	   // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
	   DiskFileItemFactory dfif = new DiskFileItemFactory();
	   dfif.setSizeThreshold(4096);// 设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时存在硬盘
	   dfif.setRepository(new File(request.getRealPath("/")
	     + "ImagesUploadTemp"));// 设置存放临时文件的目录,web根目录下的ImagesUploadTemp目录

	   // 用以上工厂实例化上传组件
	   ServletFileUpload sfu = new ServletFileUpload(dfif);
	   // 设置最大上传尺寸
	   sfu.setSizeMax(MAX_SIZE);

	   PrintWriter out = response.getWriter();
	   // 从request得到 所有 上传域的列表
	   List fileList = null;
	   try {
	    fileList = sfu.parseRequest(request);
	   } catch (FileUploadException e) {// 处理文件尺寸过大异常
	    if (e instanceof SizeLimitExceededException) {
			out.write( " <script   language=javascript> alert( '文件尺寸超过规定大小，最大尺寸为3M！ ');window.location.href= 'expandPersonalInfo.jsp'; </script> "); 
			out.flush(); 
			out.close(); 
	     return;
	    }
	    e.printStackTrace();
	   }
	   
	   // 得到所有上传的文件
	   Iterator fileItr = fileList.iterator();
	   int i=0;
	   // 循环处理所有文件
	   while (fileItr.hasNext()) {
		   
	    FileItem fileItem = null;
	    String path = null;
	    long size = 0;
	    // 得到当前文件
	    fileItem = (FileItem) fileItr.next();
	    i++;
	    // 忽略简单form字段而不是上传域的文件域(<input type="text" />等)
	    if (fileItem == null || fileItem.isFormField()) {
	    	
			if(fileItem.getFieldName().equals("name")){
				real_name = new String(fileItem.getString().getBytes("iso8859-1"), "utf8");
				
			}
			if(fileItem.getFieldName().equals("idcard")){
				identification = new String(fileItem.getString().getBytes("iso8859-1"), "utf8");
			}
			if(fileItem.getFieldName().equals("qq")){
				qq = new String(fileItem.getString().getBytes("iso8859-1"), "utf8");
			}
			if(fileItem.getFieldName().equals("tel")){
				tel = new String(fileItem.getString().getBytes("iso8859-1"), "utf8");
			}
			if(fileItem.getFieldName().equals("email")){
				email = new String(fileItem.getString().getBytes("iso8859-1"), "utf8");
			}
			if(fileItem.getFieldName().equals("changePhoto")){
				changePic = new String(fileItem.getString().getBytes("iso8859-1"), "utf8");
			}
			if(fileItem.getFieldName().equals("question")){
				question = new String(fileItem.getString().getBytes("iso8859-1"), "utf8");
			}
			if(fileItem.getFieldName().equals("answer")){
				answer = new String(fileItem.getString().getBytes("iso8859-1"), "utf8");
			}
			if(fileItem.getFieldName().equals("motto")){
				motto = new String(fileItem.getString().getBytes("iso8859-1"), "utf8");
			}
			if(fileItem.getFieldName().equals("profile")){
				profile = new String(fileItem.getString().getBytes("iso8859-1"), "utf8");
			}
	    }
	    

	    	
	    //如果是文件才进行下一步操作
	    if(!fileItem.isFormField()){
	    	if(changePic.equals("do")){
	    // 得到文件的完整路径
	    path = fileItem.getName();
	    // 得到文件的大小
	    size = fileItem.getSize();
	    if ("".equals(path) || size == 0) {
			out.write( " <script   language=javascript> alert( '请选择上传文件！ ');window.location.href= 'expandPersonalInfo.jsp'; </script> "); 
			out.flush(); 
			out.close(); 
	     return;
	    }

	    // 得到去除路径的文件名
	    String t_name = path.substring(path.lastIndexOf("\\") + 1);
	    // 得到文件的扩展名(无扩展名时将得到全名)
	    String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
	    // 拒绝接受规定文件格式之外的文件类型
	    int allowFlag = 0;
	    int allowedExtCount = allowedExt.length;
	    for (; allowFlag < allowedExtCount; allowFlag++) {
	     if (allowedExt[allowFlag].equals(t_ext))
	      break;
	    }
	    if (allowFlag == allowedExtCount) {
			out.write( " <script   language=javascript> alert( '请上传图片文件！ ');window.location.href= 'expandPersonalInfo.jsp'; </script> "); 
			out.flush(); 
			out.close(); 	
	     return;
	    }

	    long now = System.currentTimeMillis();
	    // 根据系统时间生成上传后保存的文件名
	    String prefix = String.valueOf(now);
	    // 保存的最终文件完整路径,保存在web根目录下的ImagesUploaded目录下
	    String u_name = request.getRealPath("/") + "AvatarImages/"
	      + prefix + "." + t_ext;
	    System.out.print(u_name);
	    try {
	     // 保存文件
	     fileItem.write(new File(u_name));
	     //写入数据库
		ZhuFeiUserInfoDao userInfo = new ZhuFeiUserInfoDao();
		String saveName = "AvatarImages/"
		      + prefix + "." + t_ext;
		HttpSession session = request.getSession();
		String userName = (String)session.getAttribute("username");
		//删除原来的头像
		UserInfo user = userInfo.getZhuFeiUserInfo(userName);
		String photoDir = request.getSession().getServletContext().getRealPath("\\");
		String delFile = photoDir+user.getAvatar_route();
		System.out.println("sdfasdfasdfsadfassdaf"+delFile);
		try {

			java.io.File tempFile = new java.io.File(delFile);
			tempFile.delete();
		} catch (Exception e) {
			System.out.print('e');
		}
		
		
		boolean isSucc = userInfo.updateZhuFeiUserInfo(user.getID(), user.getUsername(), user.getMail(), real_name, user.getSex(), qq, identification, tel, saveName, motto, profile, question, answer);
		
		if(isSucc){
			out.write( " <script   language=javascript> alert( '编辑个人拓展信息成功！ ');window.close(); </script> "); 
			out.flush(); 
			out.close(); 
		}else{
			out.write( " <script   language=javascript> alert( '编辑个人拓展信息失败！ ');window.location.href= 'userServlet?action=edit'; </script> "); 
			out.flush(); 
			out.close(); 				    
			}

	    } catch (Exception e) {
	     e.printStackTrace();
	    }
	    }else{
	    	//不换图片
	    	HttpSession session = request.getSession();
	    	String userName = (String)session.getAttribute("username");
			if(userName==null ||userName.equals("")){
				out.write( " <script   language=javascript> alert( '用户失效，请重新登录！ ');window.location.href= 'index.jsp'; </script> "); 
				out.flush(); 
				out.close(); 	
	    }else{
	    		ZhuFeiUserInfoDao userDao = new ZhuFeiUserInfoDao();
	    		UserInfo userInfo = userDao.getZhuFeiUserInfo(userName);
	    		boolean isSucc = userDao.updateZhuFeiUserInfo(userInfo.getID(), userName, email, real_name, userInfo.getSex(), qq, identification, tel, userInfo.getAvatar_route(), motto, profile, question, answer);
	    		if(isSucc){
					out.write( " <script   language=javascript> alert( '修改信息成功！ ');window.close(); </script> "); 
					out.flush(); 
					out.close(); 
	    		}else{
					out.write( " <script   language=javascript> alert( '修改信息失败！ ');window.close(); </script> "); 
					out.flush(); 
					out.close(); 
	    		}
	    }
	   
	    }
	    }
	  }	
		
	}

	private void edit(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf8");
		// TODO Auto-generated method stub
		HttpSession session = request.getSession();
		String username = (String)session.getAttribute("username");
		if(username==null ||username.equals("")){
			PrintWriter   out   =   response.getWriter(); 
			out.write( " <script   language=javascript> alert( '用户失效，请重新登录！ ');window.location.href= 'index.jsp'; </script> "); 
			out.flush(); 
			out.close(); 			
		}else{
		ZhuFeiUserInfoDao user = new ZhuFeiUserInfoDao();
		UserInfo userInfo = user.getZhuFeiUserInfo(username);
		session.setAttribute("userInfo", userInfo);
		response.sendRedirect("editExpandPersonalInfo.jsp");
		}
	}

	private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf8");
		String id = request.getParameter("id");
		ZhuFeiUserInfoDao userInfo = new ZhuFeiUserInfoDao();
		userInfo.getConnection();
		boolean isSucc = userInfo.deleteZhuFeiUserInfo(id);
		if(isSucc){
			PrintWriter   out   =   response.getWriter(); 
			out.write( " <script   language=javascript> alert( '删除用户成功！ ');window.location.href= 'userServlet?action=manage'; </script> "); 
			out.flush(); 
			out.close(); 
		}else{
			PrintWriter   out   =   response.getWriter(); 
			out.write( " <script   language=javascript> alert( '删除用户失败！ ');window.location.href= 'userServlet?action=manage'; </script> "); 
			out.flush(); 
			out.close(); 			
		}
	}

	private void manage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf8");
		// TODO Auto-generated method stub
		ZhuFeiUserInfoDao userInfo = new ZhuFeiUserInfoDao();
		int userCount = userInfo.getCountOfZhuFeiUserInfo();
		ArrayList userList = userInfo.getZhuFeiUserInfo(0, userCount, 3);
		HttpSession session = request.getSession();
		session.setAttribute("userList", userList);
		Paging paging = new Paging();
		//取得page值
		String strPage = paging.strPage(request, "page");
		int current_Page = paging.current_Pages(strPage);
		//设置一页显示多少行数据
		int page_record = paging.setPage_record(10);
		//取得总页数
		int total_page = paging.getTotal_Pages(userCount);
		//保存当前页数
		session.setAttribute("current_page", current_Page);
		//保存总页数
		session.setAttribute("total_page", total_page);
		session.setAttribute("page_record", page_record);
		response.sendRedirect("admin/manageUser.jsp");		
	}

	private void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf8");
			
	    	
				String real_name = null;
				String identification = null;
				String email = null;
				String qq = null;
				String tel = null;
				String motto = null;
				String profile = null;
			   final long MAX_SIZE = 3 * 1024 * 1024;// 设置上传文件最大为 3M
			   // 允许上传的文件格式的列表
			   final String[] allowedExt = new String[] { "jpg", "jpeg", "gif", "png"};
			   response.setContentType("text/html");
			   // 设置字符编码为UTF-8, 这样支持汉字显示
			   response.setCharacterEncoding("UTF-8");

			   // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
			   DiskFileItemFactory dfif = new DiskFileItemFactory();
			   dfif.setSizeThreshold(4096);// 设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时存在硬盘
			   dfif.setRepository(new File(request.getRealPath("/")
			     + "ImagesUploadTemp"));// 设置存放临时文件的目录,web根目录下的ImagesUploadTemp目录

			   // 用以上工厂实例化上传组件
			   ServletFileUpload sfu = new ServletFileUpload(dfif);
			   // 设置最大上传尺寸
			   sfu.setSizeMax(MAX_SIZE);

			   PrintWriter out = response.getWriter();
			   // 从request得到 所有 上传域的列表
			   List fileList = null;
			   try {
			    fileList = sfu.parseRequest(request);
			   } catch (FileUploadException e) {// 处理文件尺寸过大异常
			    if (e instanceof SizeLimitExceededException) {
					out.write( " <script   language=javascript> alert( '文件尺寸超过规定大小，最大尺寸为3M！ ');window.location.href= 'expandPersonalInfo.jsp'; </script> "); 
					out.flush(); 
					out.close(); 
			     return;
			    }
			    e.printStackTrace();
			   }
			   // 没有文件上传
			   if (fileList == null || fileList.size() == 0) {
					out.write( " <script   language=javascript> alert( '请选择上传文件！ ');window.location.href= 'expandPersonalInfo.jsp'; </script> "); 
					out.flush(); 
					out.close(); 
			    return;
			   }
			   // 得到所有上传的文件
			   Iterator fileItr = fileList.iterator();
			   int i=0;
			   // 循环处理所有文件
			   while (fileItr.hasNext()) {
				   
			    FileItem fileItem = null;
			    String path = null;
			    long size = 0;
			    // 得到当前文件
			    fileItem = (FileItem) fileItr.next();
			    i++;
			    // 忽略简单form字段而不是上传域的文件域(<input type="text" />等)
			    if (fileItem == null || fileItem.isFormField()) {
			    	
					if(fileItem.getFieldName().equals("name")){
						real_name = new String(fileItem.getString().getBytes("iso8859-1"), "utf8");
						
					}
					if(fileItem.getFieldName().equals("idcard")){
						identification = new String(fileItem.getString().getBytes("iso8859-1"), "utf8");
					}
					if(fileItem.getFieldName().equals("qq")){
						qq = new String(fileItem.getString().getBytes("iso8859-1"), "utf8");
					}
					if(fileItem.getFieldName().equals("tel")){
						tel = new String(fileItem.getString().getBytes("iso8859-1"), "utf8");
					}	
					if(fileItem.getFieldName().equals("motto")){
						motto = new String(fileItem.getString().getBytes("iso8859-1"), "utf8");
					}
					if(fileItem.getFieldName().equals("profile")){
						profile = new String(fileItem.getString().getBytes("iso8859-1"), "utf8");
					}
			    }
			    //如果是文件才进行下一步操作
			    if(!fileItem.isFormField()){
			    // 得到文件的完整路径
			    path = fileItem.getName();
			    // 得到文件的大小
			    size = fileItem.getSize();
			    if ("".equals(path) || size == 0) {
					out.write( " <script   language=javascript> alert( '请选择上传文件！ ');window.location.href= 'expandPersonalInfo.jsp'; </script> "); 
					out.flush(); 
					out.close(); 
			     return;
			    }

			    // 得到去除路径的文件名
			    String t_name = path.substring(path.lastIndexOf("\\") + 1);
			    // 得到文件的扩展名(无扩展名时将得到全名)
			    String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
			    // 拒绝接受规定文件格式之外的文件类型
			    int allowFlag = 0;
			    int allowedExtCount = allowedExt.length;
			    for (; allowFlag < allowedExtCount; allowFlag++) {
			     if (allowedExt[allowFlag].equals(t_ext))
			      break;
			    }
			    if (allowFlag == allowedExtCount) {
					out.write( " <script   language=javascript> alert( '请上传图片文件！ ');window.location.href= 'expandPersonalInfo.jsp'; </script> "); 
					out.flush(); 
					out.close(); 	
			     return;
			    }

			    long now = System.currentTimeMillis();
			    // 根据系统时间生成上传后保存的文件名
			    String prefix = String.valueOf(now);
			    // 保存的最终文件完整路径,保存在web根目录下的ImagesUploaded目录下
			    String u_name = request.getRealPath("/") + "AvatarImages/"
			      + prefix + "." + t_ext;
			    System.out.print(u_name);
			    try {
			     // 保存文件
			     fileItem.write(new File(u_name));
			     //写入数据库
				ZhuFeiUserInfoDao userInfo = new ZhuFeiUserInfoDao();
				String saveName = "AvatarImages/"
				      + prefix + "." + t_ext;
				HttpSession session = request.getSession();
				String userName = (String)session.getAttribute("username");
				UserInfo user = userInfo.getZhuFeiUserInfo(userName);
				boolean isSucc = userInfo.updateZhuFeiUserInfo(user.getID(), user.getUsername(), user.getMail(), real_name, user.getSex(), qq, identification, tel, saveName, motto, profile, user.getQuestion(), user.getAnswer());
				if(isSucc){
					out.write( " <script   language=javascript> alert( '添加个人拓展信息成功！ ');window.close(); </script> "); 
					out.flush(); 
					out.close(); 
				}else{
					out.write( " <script   language=javascript> alert( '添加个人拓展信息失败！ ');window.location.href= 'expandPersonalInfo.jsp'; </script> "); 
					out.flush(); 
					out.close(); 				    
					}

			    } catch (Exception e) {
			     e.printStackTrace();
			    }
			   }
			  }	
		
			
			

		
		

		}
		
	//}



	
	

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
